package com.scale.service.user.controller;

import com.example.common.result.Result;
import com.example.user.dto.UserProfileUpdateDTO;
import com.example.user.dto.PasswordUpdateDTO;
import com.example.user.vo.UserProfileVO;
import com.scale.service.user.service.UserProfileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户个人资料管理控制器
 * @author crp
 * @since 2025-09-28
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@Tag(name = "用户个人资料", description = "用户个人资料管理相关接口")
public class UserProfileController {

    @Autowired
    private UserProfileService userProfileService;

    /**
     * 获取用户详细信息
     */
    @GetMapping("/profile")
    @Operation(summary = "获取用户详细信息", description = "获取当前登录用户的详细个人资料")
    public Result<UserProfileVO> getUserProfile(HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            UserProfileVO profile = userProfileService.getUserProfile(userId);
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取用户资料失败", e);
            return Result.error("获取用户资料失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户基本信息
     */
    @PutMapping("/profile")
    @Operation(summary = "更新用户基本信息", description = "更新用户名、邮箱、手机号、性别、年龄等信息")
    public Result<String> updateUserProfile(
            @Valid @RequestBody UserProfileUpdateDTO updateDTO,
            HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            userProfileService.updateUserProfile(userId, updateDTO);
            return Result.success("用户资料更新成功");
        } catch (Exception e) {
            log.error("更新用户资料失败", e);
            return Result.error("更新用户资料失败：" + e.getMessage());
        }
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/avatar")
    @Operation(summary = "上传用户头像", description = "上传并更新用户头像")
    public Result<String> uploadAvatar(
            @Parameter(description = "头像文件") @RequestParam("avatarFile") MultipartFile avatarFile,
            HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            
            // 文件大小和格式验证
            if (avatarFile.isEmpty()) {
                return Result.error("上传文件不能为空");
            }
            
            if (avatarFile.getSize() > 5 * 1024 * 1024) {
                return Result.error("头像文件大小不能超过5MB");
            }
            
            String contentType = avatarFile.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只支持图片格式文件");
            }
            
            String avatarUrl = userProfileService.uploadAvatar(userId, avatarFile);
            return Result.success(avatarUrl, "头像上传成功");
            
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return Result.error("上传头像失败：" + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    @Operation(summary = "修改密码", description = "修改用户登录密码")
    public Result<String> updatePassword(
            @Valid @RequestBody PasswordUpdateDTO passwordDTO,
            HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            
            // 验证确认密码
            if (!passwordDTO.getNewPassword().equals(passwordDTO.getConfirmPassword())) {
                return Result.error("新密码与确认密码不一致");
            }
            
            userProfileService.updatePassword(userId, passwordDTO);
            return Result.success("密码修改成功");
            
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error("修改密码失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID（从JWT Token中解析）
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        // TODO: 实现从JWT Token中解析用户ID的逻辑
        // 这里先返回一个模拟的用户ID，实际应该从token中解析
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            // 解析JWT token获取用户ID
            // return JwtUtils.getUserIdFromToken(token.substring(7));
        }
        
        // 临时返回用户ID 1，实际应该从JWT解析
        return 1L;
    }
}
